import type { RouteRecordRaw } from "vue-router";
import { constantRoutes } from "@/router";
import { store } from "@/store";
import router from "@/router";
import { Auth } from "@/utils/auth";

import MenuAPI, { type RouteVO } from "@/api/system/menu.api";
import HmiConfigAPI from "@/api/hmi/config.api";
const modules = import.meta.glob("../../views/**/**.vue");
const Layout = () => import("@/layout/index.vue");

export const usePermissionStore = defineStore("permission", () => {
  // 存储所有路由，包括静态路由和动态路由
  const routes = ref<RouteRecordRaw[]>([]);
  // 混合模式左侧菜单路由
  const sideMenuRoutes = ref<RouteRecordRaw[]>([]);
  // 路由是否加载完成
  const routesLoaded = ref(false);

  /** hmi menu 路由数据，也不使用缓存 */
  // const hmiMenuRoutes = useStorage<any[]>("hmiMenuRoutes", [] as any[]);
  const hmiMenuRoutes = ref<any[]>([]);

  /**
   * 校验 HMI 菜单数据是否为合法 JSON 对象且含 hmimenu 字段
   */
  function parseHmiMenuData(data: any): { valid: boolean; hmimenu: any[] } {
    let json_data = data;
    if (typeof json_data === "string") {
      try {
        json_data = JSON.parse(json_data);
      } catch (e) {
        console.error("json_data 字符串转 JSON 失败:", e);
        return { valid: false, hmimenu: [] };
      }
    }
    if (!json_data || typeof json_data !== "object" || !json_data.hmimenu) {
      console.error("HMI 菜单数据格式错误，缺少 hmimenu 字段:", json_data);
      return { valid: false, hmimenu: [] };
    }
    return { valid: true, hmimenu: Array.isArray(json_data.hmimenu) ? json_data.hmimenu : [] };
  }

  /**
   * 获取后台动态路由数据，解析并注册到全局路由
   *
   * @returns Promise<RouteRecordRaw[]> 解析后的动态路由列表
   */
  function generateRoutes() {
    const isLogin = Auth.isLoggedIn();
    if (!isLogin) {
      // 未登录，返回 hmi 动态路由

      // 如果 hmiMenuRoutes 不为空，则直接返回
      if (hmiMenuRoutes.value.length > 0) {
        const hmiRoutes = parseDynamicRoutes(hmiMenuRoutes.value);
        routes.value = [...constantRoutes, ...hmiRoutes];
        routesLoaded.value = true;
        return hmiRoutes;
      }
      // 如果 hmiMenuRoutes 为空，则获取 hmi 菜单和路由
      return new Promise<RouteRecordRaw[]>((resolve, reject) => {
        HmiConfigAPI.getHmiMenuConfig()
          .then((data) => {
            const { valid, hmimenu } = parseHmiMenuData(data);
            if (!valid) {
              reject("HMI 菜单数据无效，终止路由生成");
              return;
            }
            const hmiRoutes = parseDynamicRoutes(hmimenu);
            routes.value = [...constantRoutes, ...hmiRoutes];
            routesLoaded.value = true;
            hmiMenuRoutes.value = hmimenu;
            resolve(hmiRoutes);
          })
          .catch((error) => {
            reject(error);
          });
      });
    }
    // 已登录，获取动态路由和 hmi 路由，全部路由
    // 如果已经缓存了 hmi 路由，则，请求 menuApi，合并返回
    if (hmiMenuRoutes.value.length > 0) {
      return new Promise<RouteRecordRaw[]>((resolve, reject) => {
        MenuAPI.getRoutes()
          .then((data) => {
            const dynamicRoutes = parseDynamicRoutes(data);
            const hmiRoutes = parseDynamicRoutes(hmiMenuRoutes.value);
            routes.value = [...constantRoutes, ...dynamicRoutes, ...hmiRoutes];
            routesLoaded.value = true;
            resolve([...dynamicRoutes, ...hmiRoutes]);
          })
          .catch((error) => {
            reject(error);
          });
      });
    }

    // 如果未缓存 hmi 路由，则，请求 menuApi 和 hmiApi，合并返回
    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
      Promise.all([MenuAPI.getRoutes(), HmiConfigAPI.getHmiMenuConfig()])
        .then(([menuData, hmiData]) => {
          const { valid, hmimenu } = parseHmiMenuData(hmiData);
          if (!valid) {
            reject("HMI 菜单数据无效，终止路由生成");
            return;
          }
          const dynamicRoutes = parseDynamicRoutes(menuData);
          const hmiRoutes = parseDynamicRoutes(hmimenu);
          routes.value = [...constantRoutes, ...dynamicRoutes, ...hmiRoutes];
          routesLoaded.value = true;
          hmiMenuRoutes.value = hmimenu;
          resolve([...dynamicRoutes, ...hmiRoutes]);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 仅仅添加管理员路由；管理员用户登录后，添加管理员路由
   */
  function generatreAdminRoutes() {
    return new Promise<RouteRecordRaw[]>((resolve, reject) => {
      MenuAPI.getRoutes()
        .then((data) => {
          const dynamicRoutes = parseDynamicRoutes(data);
          resolve(dynamicRoutes);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }

  /**
   * 根据父菜单路径设置侧边菜单
   *
   * @param parentPath 父菜单的路径，用于查找对应的菜单项
   */
  const updateSideMenu = (parentPath: string) => {
    const matchedItem = routes.value.find((item) => item.path === parentPath);
    if (matchedItem && matchedItem.children) {
      sideMenuRoutes.value = matchedItem.children;
    }
  };

  /**
   * 重置路由
   */
  const resetRouter = () => {
    // 创建常量路由名称集合，用于O(1)时间复杂度的查找
    // const constantRouteNames = new Set(constantRoutes.map((route) => route.name).filter(Boolean));

    // 从 router 实例中移除动态路由
    // routes.value.forEach((route) => {
    //   if (route.name && !constantRouteNames.has(route.name)) {
    //     router.removeRoute(route.name);
    //   }
    // });

    // 从 router 实例中移除动态路由，保留 hmi 路由和 constantRoutes
    const remainRoutesNames = new Set(
      [...constantRoutes, ...hmiMenuRoutes.value].map((route) => route.name).filter(Boolean)
    );

    routes.value.forEach((route) => {
      if (route.name && !remainRoutesNames.has(route.name)) {
        router.removeRoute(route.name);
      }
    });

    // 重置为仅包含常量路由
    routes.value = [...constantRoutes, ...hmiMenuRoutes.value];
    sideMenuRoutes.value = [];
    routesLoaded.value = false;
  };

  return {
    routes,
    sideMenuRoutes,
    routesLoaded,
    generateRoutes,
    generatreAdminRoutes,
    updateSideMenu,
    resetRouter,
  };
});

/**
 * 解析后端返回的路由数据并转换为 Vue Router 兼容的路由配置
 *
 * @param rawRoutes 后端返回的原始路由数据
 * @returns 解析后的路由集合
 */
const parseDynamicRoutes = (rawRoutes: RouteVO[]): RouteRecordRaw[] => {
  const parsedRoutes: RouteRecordRaw[] = [];
  // console.log("permission store parseDynamicRoutes rawRoutes", rawRoutes);
  rawRoutes.forEach((route) => {
    const normalizedRoute = { ...route } as RouteRecordRaw;

    // 处理组件路径
    normalizedRoute.component =
      normalizedRoute.component?.toString() === "Layout"
        ? Layout
        : modules[`../../views/${normalizedRoute.component}.vue`] ||
          modules["../../views/error-page/404.vue"];

    // 递归解析子路由
    if (normalizedRoute.children) {
      normalizedRoute.children = parseDynamicRoutes(route.children);
    }

    parsedRoutes.push(normalizedRoute);
  });

  return parsedRoutes;
};

/**
 * 导出此hook函数用于在非组件环境(如其他store、工具函数等)中获取权限store实例
 *
 * 在组件中可直接使用usePermissionStore()，但在组件外部需要传入store实例
 * 此函数简化了这个过程，避免每次都手动传入store参数
 */
export function usePermissionStoreHook() {
  return usePermissionStore(store);
}
